<template>
  <section class="app-inner">
    <el-dialog :visible.sync="dialogVisible"
      :before-close="handleClose" top="5vh" width="70%"
      :title="title" center modal>
      <div class="header">
        <el-form :inline="true" :model="formData"
           size="small" label-width="84px" class="searchWrapper">
            <el-form-item :label-width="40+'px'" class="line">
                <el-select filterable v-model="formData.nation" clearable placeholder="民族" class="selectWidth" auto-complete="off">
                    <el-option
                    v-for="item in nationList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item class="line">
                <el-select v-model="formData.status" clearable placeholder="状态" class="selectWidth" auto-complete="off">
                    <el-option label="禁用" value="0"></el-option>
                    <el-option label="启用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item :label-width="labelWidth" class="line">
                <el-input clearable v-model="formData.code"
                placeholder="请输入学生学籍号"></el-input>
            </el-form-item>
            <el-form-item :label-width="labelWidth" class="line">
                <el-input clearable v-model="formData.name"
                placeholder="请输入学生姓名"></el-input>
            </el-form-item>
            <el-form-item :label-width="labelWidth" class="line card-flex">
              <el-button type="primary" @click="search">搜索</el-button>
              <div class="switch-btn cursor iconfont" :class="[isShow ? 'icon-biyan': 'icon-yanjing']" @click="handleClickIsShow"></div>
            </el-form-item>
        </el-form>
      </div>
      <div class="footer">
        <el-table
            ref="multipleTable" :data="studentTableData"
            tooltip-effect="dark" style="width: 100%"
            @selection-change="handleSelectionChange" :row-key="bindRowKey">
              <el-table-column type="selection" :reserve-selection="true" width="50"></el-table-column>
              <el-table-column label="学号" width="100">
                <template slot-scope="{row}">
                  <el-input v-model="row.eduNo"
                  class="subjectSelect" auto-complete="off"></el-input>
                  <!-- <span class="spanCss" v-else @click="toEdit(row,$index)">{{row.eduNo || ''}}</span> -->
                </template>
              </el-table-column>
              <el-table-column prop="name" label="姓名" show-overflow-tooltip></el-table-column>
              <el-table-column prop="code" label="学籍号" show-overflow-tooltip></el-table-column>
              <el-table-column prop="gender" label="性别" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{scope.row.gender === 0 ? '未知性别' : scope.row.gender === 1 ? '男'
                    :  scope.row.gender === 2 ? '女' : '未说明的性别'}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="birthday" label="出生日期" show-overflow-tooltip></el-table-column>
              <el-table-column prop="account" label="账号" show-overflow-tooltip></el-table-column>
              <el-table-column prop="imageUrl" label="照片" show-overflow-tooltip>
                <template slot-scope="scope">
                  <!-- <img :src="`/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`" class="imgCss" v-show="scope.row.imageUrl!==null" /> -->
                  <el-image
                    :style="{ 'max-width': '50px', 'max-height': '50px' }"
                    :src="`/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`"
                    :preview-src-list="[
                      `/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`,
                    ]"
                  >
                    <div slot="error" class="image-slot"></div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="contact" label="联系方式" show-overflow-tooltip>
                <template v-slot='{row}'>
                  {{ !isShow ? $options.filters.cellularPhone(row.contact) : row.contact || '--' }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="账号状态" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{!scope.row.account || scope.row.status === null ? '' :
                    scope.row.status === 0 ? '禁用' : '启用'}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="nationName" label="民族" show-overflow-tooltip>
                <!-- <template slot-scope="scope">
                  <span>{{scope.row.status === 1 ? '启用' : '禁用'}}</span>
                </template> -->
              </el-table-column>
            </el-table>
            <el-pagination
                class="paginationCss"
                v-if="studentTableData.length > 0"
                layout="total, prev, pager, next"
                @current-change="changePage"
                :current-page="queryParams.pageNum"
                :page-size="queryParams.pageSize"
                :total="totalCount"
            ></el-pagination>
            <div slot="footer" class="dialog-footer">
              <el-button @click="handleCancel" size="small">取 消</el-button>
              <el-button type="primary" @click="hanldeSave('editFormRef')" size="small">确 定</el-button>
            </div>
          <div style="margin-top: 20px"></div>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { queryPage } from '../js/studentInfo.js'
import { Message } from 'element-ui'
import { addStudentNotFile } from '../js/class.js'
import { decrypt } from '@/utils/crypto'
export default {
  name: 'addStudentTable',
  components: {},
  data () {
    return {
      dialogVisible: false,
      title: '',
      showInput: false,
      labelWidth: '120px',
      formData: {},
      nationList: [], // 民族下拉框
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      type: '',
      rowData: {},
      selectedStudent: [],
      studentTableData: [],
      // pageNum: 1,
      // pageSize: 10,
      totalCount: 0,
      bindRowKey (row) {
        return row.no
      },
      multipleSelection: [],
      isShow: false
    }
  },
  computed: {},
  watch: {
    studentTableData (val) {
      val.forEach(item => {
        this.multipleSelection.forEach(self => {
          if (item.no === self.no) {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          }
        })
      })
    }
  },
  methods: {
    handleClickIsShow () {
      this.isShow = !this.isShow
    },
    // 打开弹窗
    async add ({ row, type }) {
      this.type = type
      this.rowData = row
      let nation = '民族'
      this.nationList = this.$dictionary[nation]
      await this.getStudentList(this.queryParams)
      this.dialogVisible = true
    },
    // 取消新增
    handleCancel () {
      this.$refs.multipleTable.clearSelection()
      Object.assign(this.$data, this.$options.data())
      this.dialogVisible = false
    },
    // 获取学生列表信息
    async getStudentList (data) {
      let res = await queryPage(data)
      if (res.code === 0) {
        let data = JSON.parse(decrypt(res.data))
        this.totalCount = data.total
        this.studentTableData = data.records
      }
    },
    // 切换输入input / span
    toEdit (row, index) {
      row.isEdit = true
    },
    // 失去焦点，显示span
    toLook (row) {
      let value = row.eduNo
      if (!value.trim()) {
        this.$message.error('输入内容为空')
        row.eduNo = ''
        return
      }
      row.isEdit = false
      this.showInput = false
    },
    // 关闭弹窗
    handleClose () {
      Object.assign(this.$data, this.$options.data())
      this.$refs.multipleTable.clearSelection()
      this.dialogVisible = false
    },
    // 搜索
    search () {
      this.queryParams.pageNum = 1
      // this.formData.status = +this.formData.status
      let query = Object.assign({}, this.queryParams, this.formData)
      if (query.status) {
        query.status = +query.status
      }
      this.getStudentList(query)
    },
    // 表格选中项触发
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 更改页数
    async changePage (val) {
      this.queryParams.pageNum = val
      let query = Object.assign({}, this.queryParams, this.formData)
      if (query.status) {
        query.status = +query.status
      }
      let res = await queryPage(query)
      if (res.code === 0) {
        this.setArr()
        const records = res.data.records
        records.forEach((item, index) => {
          this.multipleSelection.forEach(mItem => {
            if (mItem.no === item.no) {
              res.data.records[index] = mItem
            }
          })
        })
        this.studentTableData = res.data.records
      }
    },
    // 选中的数据处理
    setArr () {
      let teacherArr = []
      let obj = {}
      this.multipleSelection.forEach((item) => {
        if (obj[item.no]) {
          return 0
        } else {
          obj[item.no] = true
          teacherArr.push(item)
        }
        // obj[item.code] ? '' : obj[item.code] = true && teacherArr.push(item)
      })
      this.multipleSelection = teacherArr
    },
    async hanldeSave () {
      let flag = 0
      let students = []
      let eduRepeat = []
      this.multipleSelection.forEach(item => {
        eduRepeat.push(item.eduNo)
        if (!item.eduNo) {
          flag = 1
        }
        let obj = {}
        obj.eduNo = item.eduNo // 学号
        obj.studentNo = item.no // 学生编号
        students.push(obj)
      })
      if (flag) {
        Message({
          type: 'error',
          message: '请输入学生班内学号'
        })
        // Message.warning('请输入学生班内学号')
        return
      }
      if (this.type === 'addClassInto') {
        // 新增班级打开的弹框
        let setRepeat = [...new Set(eduRepeat)] // 已输入的学号去重
        if (setRepeat.length < eduRepeat.length) {
          this.$alert(`班内学号已重复！`, '提示', {
            confirmButtonText: '确定'
          })
          return
        }
        let resultData = {
          row: this.multipleSelection,
          students
        }
        // 判断是否有重复的学号或重复的学生
        await this.$emit('checkedEduNo', students)
        if (!this.$parent.eduErr) {
          // 班内学号没有重复
          if (!this.$parent.stuNoErr) {
            // 班内学生没有重复 允许添加
            this.$emit('getResultAddStudent', resultData)
            this.dialogVisible = false
            Object.assign(this.$data, this.$options.data())
            this.$refs.multipleTable.clearSelection()
          } else {
            let tips = ''
            this.$parent.stuNoErrArr.forEach(item => {
              tips = item + ' ' + tips
            })
            this.$alert(`学生：${tips}在该班级中已存在`, '提示', {
              confirmButtonText: '确定',
              callback: () => {
                this.$parent.stuNoErrArr = []
              }
            })
          }
        } else {
          // 班内学号重复
          let tips = ''
          this.$parent.eduErrArr.forEach(item => {
            tips = item + ' ' + tips
          })
          this.$alert(`学生：${tips}的班内学号在该班级中已存在`, '提示', {
            confirmButtonText: '确定',
            callback: () => {
              this.$parent.eduErrArr = []
            }
          })
        }
      } else {
        // 学生管理中打开的弹框，给班级下新增学生
        await this.reqStudent()
      }
    },

    async reqStudent () {
      let students = []
      this.multipleSelection.forEach(item => {
        let obj = {}
        obj.eduNo = item.eduNo // 学号
        obj.studentNo = item.no // 学生编号
        students.push(obj)
      })
      let query = {
        classNo: this.rowData.classNo,
        students
      }
      try {
        let res = await addStudentNotFile(query)
        if (res.code === 0) {
          this.$emit('selectStudent')
          this.dialogVisible = false
          Object.assign(this.$data, this.$options.data())
          this.$refs.multipleTable.clearSelection()
        } else {
          Message({
            type: 'error',
            message: res.msg
          })
        }
      } catch (e) {
      }
    }
  },
  mounted () {}
}
</script>
<style scoped lang="scss">
.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
.paginationCss {
  text-align: right;
}
.subjectSelect {
  width: 80px;
  height: 30px;
  margin-bottom: 3px;
}
.spanCss {
  display: inline-block;
  width: 80px;
  height: 30px;
}
/deep/ .el-input__inner {
  height: 25px;
}
.imgCss {
  width: 40px;
  height: 40px;
}
</style>
